package com.atguigu.gulimall.product.sync;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo3 {
    public static void main(String[] args) {
        ShareResource share = new ShareResource();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.print5(i);
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.print10(i);
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.print15(i);
            }
        }, "CC").start();
    }

}

class ShareResource {

    private int flag = 1;

    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void print5(int loop) {
        try {
            lock.lock();
            while (flag != 1) {
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "::" + i + "：轮数：" + loop);
            }
            flag=2;
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print10(int loop) {
        try {
            lock.lock();
            while (flag != 2) {
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "::" + i + "：轮数：" + loop);
            }
            flag=3;
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print15(int loop) {
        try {
            lock.lock();
            while (flag != 3) {
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "::" + i + "：轮数：" + loop);
            }
            flag=1;
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }
}